package com.example.jdai.jdai.threeparty;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;
import android.util.Log;

import com.example.jdai.jdai.config.Config;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by hellopyj on 2017/2/9.
 */

public class SmsReceiver extends BroadcastReceiver {
    private static MessageListener mMessageListener;
    public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";
    @Override
    public void onReceive(Context context, Intent intent) {
        if(Config.ISDEBUG)
            Log.v("smsr","ok");
        if (intent.getAction().equals(SMS_RECEIVED_ACTION)) {
            Object[] pdus = (Object[]) intent.getExtras().get("pdus");
            for(Object pdu:pdus) {
                SmsMessage smsMessage = SmsMessage.createFromPdu((byte [])pdu);
                String sender = smsMessage.getDisplayOriginatingAddress();
                //短信内容
                String content = smsMessage.getDisplayMessageBody();
                if(Config.ISDEBUG)
                Log.v("smsr",content);
                //long date = smsMessage.getTimestampMillis();
                //Date tiemDate = new Date(date);
                //SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
               // String time = simpleDateFormat.format(tiemDate);
                    mMessageListener.onReceived(doSelect(content));
                    abortBroadcast();
            }
        }

    }

    //回调接口
    public interface MessageListener {
        public void onReceived(String message);
    }

    public void setOnReceivedMessageListener(MessageListener messageListener) {
        this.mMessageListener = messageListener;
    }
    String doSelect(String content){
        if(-1!=content.indexOf("江湖盘缠")){
            Pattern continuousNumberPattern = Pattern.compile("[0-9\\.]+");
            Matcher m = continuousNumberPattern.matcher(content);
            String dynamicPassword = "";
            while(m.find()){
                if(m.group().length() == 4) {
                    System.out.print(m.group());
                    dynamicPassword = m.group();
                    }
                }
            return dynamicPassword;
        }
        else
        {
            return "";
        }

    }
}
